var vscode = require("vscode");
const path = require('path');
const { cmd_run_lua, War3Helper } = require('./src/lua');

/**
 * 插件被激活时触发，所有代码总入口
 * @param {vscode.ExtensionContext} context 插件上下文
 */
exports.activate = async function (context) {
    console.log('初始化插件war3helper');

    await require('./src/custom_plugin')(context);
    await require('./src/info')(context);

    const parentDir = path.dirname(__filename);
    const config = vscode.workspace.getConfiguration();

    // 读取设置项的值
    if (config.get('war3helper.EnableLualib')) {
        // 1. 设置环境变量
        process.env.War3HelperPath = parentDir;

        // 2. 生成 clua_meta 的绝对路径
        const lualibPath = path.join(parentDir, 'plugin', 'Include', 'clua_meta');

        // 3. 更新 Lua.workspace.library 配置
        const currentLibrary = config.get('Lua.workspace.library') || [];
        const lualibFileName = path.basename(lualibPath);

        const updatedLibrary = currentLibrary.map(libPath => {
            if (path.basename(libPath) === lualibFileName) {
                return lualibPath;
            }
            return libPath;
        });
        if (!updatedLibrary.includes(lualibPath)) {
            updatedLibrary.push(lualibPath);
        }
        try {
            await config.update(
                'Lua.workspace.library',
                updatedLibrary,
                vscode.ConfigurationTarget.Workspace
            );
            War3Helper.info('✅ 更新配置:Lua.workspace.library 成功!');
        } catch (error) {
            War3Helper.warn('❌ 更新配置:Lua.workspace.library 失败!', error);
        }
        War3Helper.hide()
        War3Helper.show()
    }

    const RunLuaScript = vscode.commands.registerCommand('war3helper.RunLuaScript', async function (uri) {
        if (uri && uri.fsPath.endsWith('.lua')) {
            vscode.window.showInformationMessage(`运行Lua文件： ${uri.fsPath}`);
            cmd_run_lua(uri.fsPath);
        }
    });
    context.subscriptions.push(RunLuaScript);
};


/**
 * 插件被释放时触发
 */
exports.deactivate = async function () {
    await global.cluaSocket.closeCLua();
    console.log('卸载war3helper插件')
};